package delayMessage.queue;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 延迟任务的任务体
 *
 * Created by Zhou_Bing on 2018/9/29.
 */
public class Message implements Delayed{

    private int id;
    private String body;//消息内容
    private Long executeTime;//任务执行时间


    Message(int id, String body, long delayTime){
        this.id = id;
        this.body = body;
        this.executeTime = TimeUnit.NANOSECONDS.convert(delayTime,TimeUnit.MILLISECONDS)+System.nanoTime();
    }

    public int getId(){
        return this.id;
    }

    public String getBody(){
        return this.body;
    }

    /**
     *  延迟任务是否到时 是按照这个方法进行判断的
     *
     *  返回负数表明还没到期
     * @param unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.executeTime-System.nanoTime(),TimeUnit.NANOSECONDS);
    }


    /**
     * 用于延迟队列的排序
     *
     * 在上面的，先执行
     *
     * @param o
     * @return
     */
    @Override
    public int compareTo(Delayed o) {
        Message job = (Message) o;
        return Integer.compare(this.id,job.id);
    }
}
